package com.handinfo.uimenu.window;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.Graphics;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameManager;
import com.handinfo.uimenu.UIAbstractWindow;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIMessageBox;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;

public class UIAutoHangUp extends UIAbstractWindow
{
    public byte m_state = 0;//状态： 0自动打怪 1购买双倍
    public final String[] m_title_name = {"自动打怪","购买增倍"};
    public final String[] m_lable = {"使用数目：","当前增倍时间：","付费货币：","购买总价：","当前拥有：","当前拥有："};
    public final String m_infos = "功能包括："+Tools.CHANGE_ROW+"　　自动打怪，自动使用红药和蓝药，自动修理装备。";
    public long m_time;//当前使用挂机符时间
    public byte m_j;//经验倍数
    public byte m_q;//金钱倍数
    public String[] m_title;//标题介绍信息
    public String[] m_buy_infos;//购买内容信息
   
    private static final int WORD_W = UITools.IW_RECTS;//单元列间距
	private static final int WORD_H = UITools.IH_RECTS;//单元行间距
	private static final int LIST_RECT_H = AbstractGameScreen.FONT_H; //单元列表的高
	private static final int TitleColour = 0xFFFF00;//颜色
	private static final int TITLE_MAXLINE = 5;//标题最大行数
	private static final int TITLE_H = LIST_RECT_H * TITLE_MAXLINE + 2*WORD_H;//标题公告信息框的高
	private static final int LIST_H = (UITools.H_RECT - TITLE_H - 2*WORD_H);//列表实际高
	private final int m_w_content = UITools.W_RECT;//上下框的宽
	private final int m_buy_width = AbstractGameScreen.FONT_W * 6;
	
	public UIAutoHangUp(int id)
	{
		super(id);
	}
    
	public void init(){
		switch(m_state){
			case 0:
				setBounds(UITools.X_BG, UITools.Y_BG, UITools.W_BG, UITools.H_BG);
				m_title = Tools.getStrArray(m_infos, m_w_content - 4*WORD_W);
				setInfos();
				break;
			case 1:
				int X_SEND = 20;// 相对list界面的宽度
				int Y_SEND = 40;
				setBounds(UITools.X_BG + X_SEND, UITools.X_BG + Y_SEND, UITools.W_BG - (X_SEND << 1), UITools.H_BG - (Y_SEND << 1));
				break;
		}
	}
	
	protected void setInfos()
	{
		StringBuffer buff = new StringBuffer();
		buff.append("当前拥有增倍时间：");
		buff.append(""+Tools.CHANGE_ROW);
		if( m_time <=0 ){
			buff.append("没有使用增倍！");
		}else{
			buff.append("　　");
			final int model = 60 * 24;
			long day = m_time/model;
			long min = m_time%model;
			long hour = min/60;
			if( day >= 1 ){
				buff.append(day+"天");	
			}
			if( hour >= 1 ){
				buff.append(hour+"小时");
				min %= 60;	
			}
			buff.append(min+"分钟");
		}
		buff.append(""+Tools.CHANGE_ROW);
		
		buff.append("购买增倍后："+Tools.CHANGE_ROW+"　　获得经验"+m_j+"倍");
		if( m_q>1 ){
			buff.append("与金钱"+m_q+"倍。");
		}else{
			buff.append("。");
		}
		m_buy_infos = Tools.getStrArray(buff.toString(), m_w_content - 4*WORD_W);
		buff = null;
	}
	protected void paintContent(Graphics g)
	{
		//绘制背景
		UITools.paintBackGround(g, m_x, m_y, m_w, m_h, m_title_name[m_state], true, true);
		if( m_state == 1 ){
			paintCommon(g);
		}else{
			paintInfos(g);
		}
	}
    
	protected void paintInfos(Graphics g){
		int tempX = m_x + UITools.INITX_CONTENT;
		int tempY = m_y + UITools.INITY_CONTENT;
		//绘制上框
		UITools.paintContentRect(g, tempX, tempY, m_w_content, TITLE_H);
		//绘制上框内容
		if( m_title != null ){
			g.setColor(TitleColour);
			tempX = m_x + UITools.INITX_CONTENT + 2*WORD_W;
			tempY = m_y + UITools.INITY_CONTENT + WORD_H;
			g.setClip(tempX, tempY, m_w_content, TITLE_H - 2*WORD_H);
			for( int i=0;i<m_title.length;i++ ){
				g.drawString(m_title[i], tempX, tempY+i*LIST_RECT_H, 0);
			}
		}
		//绘制下框
		g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		tempX = m_x + UITools.INITX_CONTENT;
		tempY = m_y + UITools.INITY_CONTENT + TITLE_H + WORD_H;
		UITools.paintContentRect(g, tempX, tempY, m_w_content, LIST_H);
		
		//显示选择框
		g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		tempX = (m_x+((m_w - m_buy_width) >> 1));
		tempY = m_y + UITools.INITY_CONTENT + TITLE_H + 3*WORD_H;
        UITools.paintLabelStr(g, tempX, tempY, m_buy_width, UITools.H_LABEL_STR, m_title_name[1],true,true);
        
      //绘制下框内容
		if( m_buy_infos != null ){
			tempX = m_x + UITools.INITX_CONTENT + 2*WORD_W;
			tempY = tempY + WORD_H + UITools.H_LABEL_STR;
			g.setClip(tempX, tempY, m_w_content, TITLE_H - 2*WORD_H);
			for( int i=0;i<m_buy_infos.length;i++ ){
				 g.setColor(TitleColour);
				 if( i== 1 ){
					 g.setColor(0xFF0000);
				 }
				g.drawString(m_buy_infos[i], tempX, tempY+i*LIST_RECT_H, 0);
			}
		}
	}
	
	
	private String STR_YONGYOU = "当前拥有";
	private String STR_SUM = "购买总价";
	private String STR_LABEL_YP = "银票";
	private String STR_LABEL_RMB = "元宝";
	private String STR_NUM = "购买小时数:";
	private boolean m_is_selYinpiao;// 是否选中的是银票
	private long m_price_yinpiao;
	private long m_price_rmb;
	private int m_num = 1;
	private int m_num_max = 99;
	
	private final int INDEX_NUM = 1;
	private final int INDEX_YINPIAO = 2;
	private final int INDEX_RMB = 3;
	
	private void paintCommon(Graphics g) {
		int initX = m_x + UITools.INITX_CONTENT;
		int tempX = initX;
		int endX = m_x + m_w - UITools.IW_WIN;
		// 元宝数目
		int tempY = m_y + m_h - (UITools.H_BUTTON + UITools.IW_WIN + UITools.IH_RECTS);
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
		g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
		UITools.paintMoneyRmbRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_rmb, false);
		// 银票数目
		tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
		g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
		UITools.paintMoneyYinpiaoRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_yinpiao, false);
		// 购买总价
		tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
		g.setColor(Tools.GREEN);
		g.drawString(STR_SUM, tempX, tempY, Tools.LEFT_BOTTOM);
		if (m_is_selYinpiao) {
			UITools.paintMoneyYinpiaoRB(g, endX, tempY, getSumMoney(), false);
		} else {
			UITools.paintMoneyRmbRB(g, endX, tempY, getSumMoney(), false);
		}
		// 标签（银票，元宝）
		tempY -= ((AbstractGameScreen.FONT_H + UITools.IH_RECTS) + UITools.H_LABEL_STR);
		int W_BUY_MONEY = (AbstractGameScreen.FONT_W << 1) + 2;// 标签的宽度
		tempX = endX - W_BUY_MONEY - UITools.IW_RECTS;

		UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_RMB, !m_is_selYinpiao);
		if (m_index == INDEX_RMB) {
			UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
		}
		if (isSupportYinpiao()) {
			tempX -= (W_BUY_MONEY + UITools.IW_RECTS);
			UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_YP, m_is_selYinpiao);
			if (m_index == INDEX_YINPIAO) {
				UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
			}
		}
		g.setColor(Tools.GREEN);
		g.drawString("付费货币:", initX, tempY, 0);

		// 输入数目
		tempX = initX;
		tempY -= (UITools.H_LABEL_STR + UITools.IH_RECTS);
		if (m_num_max > 0) {
			g.setColor(Tools.GREEN);
			g.drawString(STR_NUM, tempX, tempY, 0);
			int W_NUM_INPUT = 40;
			int H_NUM_INPUT = AbstractGameScreen.FONT_H + 4;
			paintNumInput(g, endX - W_NUM_INPUT - 9, tempY, W_NUM_INPUT, H_NUM_INPUT, m_num);
		}
	}
	
	private void paintNumInput(Graphics g, int x, int y, int w, int h, int num) {
		int IW_NUM_ARR_RECT = 9;
		if (m_index == INDEX_NUM) {
			int[] colors = new int[] { 0x4f0000, 0x00ffea, 0x00ffea };
			for (int i = 0, length = colors.length; i < length; i++) {
				UITools.drawRect(g, x, y, w, h, colors[i], i);
			}
		} else {
			UITools.paintContentRect(g, x, y, w, h);
		}
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
		g.drawString(String.valueOf(num), x + w - UITools.IW_RECT_CONTENT, y + UITools.IH_RECT_CONTENT, Tools.RIGHT_TOP);
		int tempY = y + ((h + UIManager.IMAGE_ARR_DARK.getWidth()) >> 1);
		Tools.drawRegion(g, UIManager.IMAGE_ARR_DARK, x - IW_NUM_ARR_RECT, tempY, Tools.TRANS_90, Tools.LEFT_BOTTOM);// 左
		Tools.drawRegion(g, UIManager.IMAGE_ARR_DARK, x + w + IW_NUM_ARR_RECT - UIManager.IMAGE_ARR_DARK.getHeight() + 1, tempY, Tools.TRANS_270, Tools.LEFT_BOTTOM);// 右
	}
	
	protected void keyBuyLogic() {
		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
			actionLeftSoft();
		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
			close();
		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
			dirUpDown();
		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
			dirUpDown();
		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT) || AbstractGameScreen.haveKeyHold(AbstractGameScreen.GK_LEFT)) {
			if (m_index == INDEX_NUM) {
				if (m_num_max <= 0) {
					return;
				}
				if (m_num <= 1) {
					changeNum(m_num_max);
				} else {
					changeNum(m_num - 1);
				}
			} else {
				dirLeftRight();
			}
		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT) || AbstractGameScreen.haveKeyHold(AbstractGameScreen.GK_RIGHT)) {
			if (m_index == INDEX_NUM) {
				if (m_num_max == 0) {
					return;
				}
				if (m_num >= m_num_max) {
					changeNum(1);
				} else {
					changeNum(m_num + 1);
				}
			} else {
				dirLeftRight();
			}
		}
	}
	
	/**
	 * 2012-4-24 下午06:54:20 venizeng
	 * 
	 * @param i
	 */
	private void changeNum(int num) {
		m_num = num;
	}
	
	private void actionLeftSoft() {
		if (isMoneyEnough()) {// 金钱足够
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
			messageBox.setMessage(getLeftSoftAlertStr());
			messageBox.addListener(new UIListener() {

				public void actionPerformed() {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						GameManager.getInstance().m_game_message.sendBuyTwo(m_is_selYinpiao, m_num);
						close();
						UIManager.getInstance().removeWindow(messageBox);
					} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						UIManager.getInstance().removeWindow(messageBox);
					}
				}
			});
		} else {
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
			String temp = m_is_selYinpiao ? "银票不足，您可以充值元宝进行消费" : "元宝不足，请您先进行充值";
			messageBox.setMessage(temp);
			messageBox.addListener(new UIListener() {

				public void actionPerformed() {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						UIChongzhi.gotoChongzhi();
						UIManager.getInstance().removeWindow(messageBox);
					} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						UIManager.getInstance().removeWindow(messageBox);
					}
				}
			});
		}
	}
	
	private String getLeftSoftAlertStr() {
		final int COLOR_NUM = Tools.GREEN;
		final int COLOR_NAME = Tools.RED;
		String temp = m_is_selYinpiao ? "银票" : "元宝";
        return "购买" + "<mark c=" + COLOR_NUM + ">" + m_num + "</mark>" + "小时" + "<mark c=" + COLOR_NAME + ">" + "挂机双倍" + "</mark>" + "将消耗" + "<mark c=" + COLOR_NUM + ">"
					+ getSumMoney() + "</mark>" + temp;
	}
	
	private void dirUpDown() {
		switch (m_index) {
		case INDEX_NUM:
			if (isSupportYinpiao()) {
				setBuyIndex(INDEX_YINPIAO);
			} else {
				setBuyIndex(INDEX_RMB);
			}
			break;
		case INDEX_YINPIAO:
		case INDEX_RMB:
		default:
			if (isSupportNum()) {
				setBuyIndex(INDEX_NUM);
			}
			break;
		}
	}
     
	private void dirLeftRight() {
		switch (m_index) {
		case INDEX_YINPIAO:
			setBuyIndex(INDEX_RMB);
			break;
		case INDEX_RMB:
			if (isSupportYinpiao()) {// 不支持银票
				setBuyIndex(INDEX_YINPIAO);
			}
			break;
		}
	}

	private boolean isMoneyEnough() {
		if (m_is_selYinpiao) {
			return GameManager.getInstance().m_role.m_money_yinpiao >= getSumMoney();
		} else {
			return GameManager.getInstance().m_role.m_money_rmb >= getSumMoney();
		}
	}
	
	/**
	 * 设置谁获得焦点 2012-4-24 下午06:48:41 venizeng
	 * 
	 * @param iNDEXRMB
	 */
	private void setBuyIndex(int index_buy) {
		m_index = index_buy;
		switch (m_index) {
		case INDEX_NUM:
			break;
		case INDEX_YINPIAO:
			m_is_selYinpiao = true;
			break;
		case INDEX_RMB:
			m_is_selYinpiao = false;
			break;
		}
	}
	
	private boolean isSupportNum() {
		return m_num_max != 0;
	}
	
	private boolean isSupportYinpiao() {
		return m_price_yinpiao != 0;
	}
	
	private long getSumMoney() {
		if (m_is_selYinpiao) {
			return m_num * m_price_yinpiao;
		} else {
			return m_num * m_price_rmb;
		}
	}
	
	protected void setState(int state){
		m_state = (byte)state;
	}
	
	protected void keyLogic()
	{
		switch(m_state){
			case 0:
				if(AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)){
					close();
				}else if(AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
						||AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)){
					 GameManager.getInstance().m_game_message.sendOpenBuyTwo();
					//testOpenBuyTwo();
				}
				break;
			case 1:
				keyBuyLogic();
				break;
		}
		
	}
	
	
	/**
	 * 接收数据创建自动挂机
	 * */
	public static final void recvAutoHangUp(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvAutoHangUp");	
			UIAutoHangUp  win = (UIAutoHangUp)UIWindowFactory.createWindow(UIWindowFactory.WINDOW_ID_AUTOHANGUP);
			byte state = 0;
			win.setState(state);
			win.m_j = dis.readByte();//经验倍数
			win.m_q = dis.readByte();//金钱倍数
			win.m_time = dis.readLong();
			Tools.debugPrintln("win.m_j="+win.m_j);
			Tools.debugPrintln("win.m_q="+win.m_q);
			Tools.debugPrintln("win.m_time="+win.m_time);
            win.init();
		    UIManager.getInstance().addWindow(win);
			dis.close();
			dis = null;
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	/**
	 * 接收数据创建自动挂机
	 * */
	public static final void recvOpenBuyTwo(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvOpenBuyTwo");
			GameManager.getInstance().m_game_message.unlockNetwork();	
			UIAutoHangUp  win = (UIAutoHangUp)UIWindowFactory.createWindow(UIWindowFactory.WINDOW_ID_AUTOHANGUP);
			byte state = 1;
			win.setState(state);
			win.m_price_yinpiao = dis.readLong();
			win.m_price_rmb = dis.readLong();
			win.m_num_max = dis.readShort();
			win.dirUpDown();
            win.init();
		    UIManager.getInstance().addWindow(win);
			dis.close();
			dis = null;
		}
		catch (Exception e) {
			GameManager.getInstance().m_game_message.unlockNetwork();
			Tools.debug(e);
		}
	}
	
	/**
	 * 接收数据创建自动挂机
	 * */
	public static final void recvBuyTwo(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvBuyTwo");	
			byte state = dis.readByte();
			String content = "";
			if( state == 1){
				content = "购买成功！";
			}else{
				content = "购买失败！";
			}
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, content);
			dis.close();
			dis = null;
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	/**
	 * 接收数据创建自动挂机
	 * */
	public static final void recvUpdateTime(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvUpdateTime");	
			long time = dis.readLong();
			int size = UIManager.getInstance().m_wins.size();
			for(int i=size-1;i>=0;i--){
				if( UIManager.getInstance().getWindowAt(i) instanceof UIAutoHangUp ){
					UIAutoHangUp win = (UIAutoHangUp)UIManager.getInstance().getWindowAt(i);
					if( win != null && win.m_state == 0){
						synchronized (win) {
							win.m_time = time;
							win.setInfos();
						}
						break;
					}
				}
			}
			dis.close();
			dis = null;
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	
//	public static void testUIAutoHangUp()
//	{
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		DataOutputStream dos = new DataOutputStream(baos);
//		try {
//			int jingyan = 2;
//			int jinqian = 3;
//			long time = 2004;
//			dos.writeInt(jingyan);
//			dos.writeInt(jinqian);
//			dos.writeLong(time);
//		}
//		catch (Exception e) {
//			// TODO: handle exception
//		}
//		ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
//		DataInputStream dis = new DataInputStream(das);
//		try {
//			recvAutoHangUp(dis);
//		}
//		catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
//	
//	public static void testOpenBuyTwo()
//	{
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		DataOutputStream dos = new DataOutputStream(baos);
//		try {
//            long yinpiao = 1;
//            long rmb = 20;
//            short max = 50;
//			dos.writeLong(yinpiao);
//			dos.writeLong(rmb);
//			dos.writeShort(max);
//		}
//		catch (Exception e) {
//			// TODO: handle exception
//		}
//		ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
//		DataInputStream dis = new DataInputStream(das);
//		try {
//			recvOpenBuyTwo(dis);
//		}
//		catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

}
